package route

import (
	"fmt"
	"net/http"
	"reflect"
	"strings"
	"w3c/controller"
)

func FirstUpper(s string) string {
	if s == "" {
		return ""
	}
	return strings.ToUpper(s[:1]) + s[1:]
}

func Dispatcher(w http.ResponseWriter, r *http.Request) error {
	r.ParseForm()

	p := controller.Routes{}
	v := reflect.ValueOf(p)
	fn := FirstUpper(r.URL.Path[1:])

	if fn == "" {
		fn = "Index"
	}

	m := v.MethodByName(fn)

	if !m.IsValid() {

		w.WriteHeader(404)
		err := fmt.Errorf("err %s", "sorry ,route is not exists")
		return err

	}

	args := []reflect.Value{reflect.ValueOf(w), reflect.ValueOf(r)}
	m.Call(args)
	return nil

}
